//
//  ViewController.m
//  UISearchBarDemo
//
//  Created by 尤春芬 on 2017/6/7.
//  Copyright © 2017年 Yuna. All rights reserved.
//

#import "ViewController.h"
#import "YCFSearchBarView.h"

#define WEAK_SELF(weakSelf)  __weak __typeof(&*self)weakSelf = self;
#define iOS9 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)


@interface ViewController ()<UITableViewDataSource, UITableViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate> {\
    
    NSMutableArray *searchListData;
    NSMutableArray *orginListData;
    
}


@property(nonatomic,strong)UITableView *myTableView;

@property(nonatomic,strong)UISearchController *mySearchBar;


@property(nonatomic,strong)YCFSearchBarView *searchHeadView;


@end

@implementation ViewController

static NSString *teamCellID = @"TeamCell";

#pragma mark searchBar

- (UISearchController *)mySearchBar {
    
    if (!_mySearchBar) {
        _mySearchBar = [[UISearchController alloc]initWithSearchResultsController:nil];
        _mySearchBar.delegate =self;
        _mySearchBar.searchResultsUpdater = self;
        // //搜索时，背景变暗色
        _mySearchBar.dimsBackgroundDuringPresentation = false;
        //隐藏导航栏
        _mySearchBar.searchBar.delegate = self;
        _mySearchBar.searchBar.placeholder = @"请输入工号或姓名";
        _mySearchBar.hidesNavigationBarDuringPresentation = NO;
        [_mySearchBar.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
        [_mySearchBar.searchBar sizeToFit];
        _mySearchBar.dimsBackgroundDuringPresentation = NO;//是否显示灰色透明的蒙版
        //  在iOS9中报这个问题 [Warning] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UISearchController: 0x7fcdbc0392d0>)
        if (iOS9) {
            [_mySearchBar loadViewIfNeeded];
        }
    }
    
    return _mySearchBar;
}

- (YCFSearchBarView *)searchHeadView{
    
    if (!_searchHeadView) {
        _searchHeadView = [[YCFSearchBarView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 44)];
    }
    return _searchHeadView;
}

- (UITableView *)myTableView {
    
    if (!_myTableView) {
        
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.frame = self.view.frame;
        _myTableView.separatorColor = [UIColor clearColor];
        _myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:teamCellID];
        
//        _myTableView.tableHeaderView = self.mySearchBar.searchBar;
        _myTableView.tableHeaderView = self.searchHeadView;

    }
    return _myTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.myTableView];
    
    //UITableView开始滚动到的位置（这样一开始headerView是不显示的）
    [_myTableView setContentOffset:CGPointMake(0.0, 44.0) animated:NO];
    
    searchListData = [NSMutableArray array];
    orginListData = [NSMutableArray array];
    
    for (int i = 0; i < 20; i++) {
        [searchListData addObject:[NSString stringWithFormat:@"%d",i*10]];
        [orginListData addObject:[NSString stringWithFormat:@"%d",i]];
    }


    
    WEAK_SELF(weakSelf)
    
    #pragma mark 搜索掉接口
    
    weakSelf.searchHeadView.searchSomeInfo = ^(NSString *searchStr) {
      
        if ([weakSelf isPureInt:searchStr]) {
            if (searchStr.length == 11) {//输入的都是数字且是11为就去掉接口
//                if (TTYDEF_CFLAG) { //判断手机号码格式对不对  但是这又有个问题就是若是昵称就是4位数字呢  若是昵称就是数字加文字呢  判断是否都是数字
//
//                }
            }else{
                
            }
        }
        
        [weakSelf.view endEditing:YES];
        
    };

}
#pragma mark 输入的字符串是否都是数字
- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - UISearchBarDelegate 搜索取消时，显示原始全部数据

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    if(_mySearchBar.searchBar.text.length == 0){
        [searchListData setArray:orginListData];
        [_myTableView reloadData];
    }
}


#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (_mySearchBar.active) {
        
        return searchListData.count;
    }
    return orginListData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:teamCellID forIndexPath:indexPath];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:teamCellID];
    }
     if (_mySearchBar.active) {
         cell.textLabel.text = searchListData[indexPath.row];
     }else{
         cell.textLabel.text = orginListData[indexPath.row];
     }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    
    if (_mySearchBar.active) {
        
    
        
    }else{
        
        
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.mySearchBar.active) {
        self.mySearchBar.active = NO;
        [self.mySearchBar.searchBar removeFromSuperview];
    }
}

#pragma mark - searchController delegate

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    if(searchController.searchBar.text.length != 0){
        
//        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.userName CONTAINS %@ || SELF.realName CONTAINS %@", searchController.searchBar.text,searchController.searchBar.text];
        
//        if (searchListData!= nil) {
//            [searchListData removeAllObjects];
//        }
//        searchListData= [[orginListData filteredArrayUsingPredicate:predicate] mutableCopy];
//        AppLog(@"--------------------%@",searchListData);
        
        WEAK_SELF(weakSelf)
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.myTableView reloadData];
        });
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            if (searchListData.count == 0) {
                NSLog(@"no data~~~");
//                if (weakSelf.fromWhichView==1) {
//                    [MBProgressHUD showError:@"该员工不符合换班规则" toView:weakSelf.view];
//                    
//                }else{
//                    [MBProgressHUD showError:@"暂无更多信息" toView:weakSelf.view];
//                    
//                }
            }
            
        });
        
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
